import Qfpage  from "../../components/Qfpage/Qfpage";
import React from 'react';
import 'antd/dist/antd.css';
import {  
    Table, 
    Button,
    Drawer , 
    Form, 
    Input, 
    InputNumber,
    notification,
    Modal,
    Col, 
    Row, 
    Radio,
    Cascader,
    Select,
    Tag,
} from 'antd';
import { useMemo,useEffect,useState, useRef,useCallback,useLayoutEffect} from "react";
import { getAllRoom, addRoom,delRoom,editRoom} from "../../api/room";
import {getAllBuild} from '../../api/build'
import {getAllType} from  '../../api/roomType'




const RoomList=()=>{ 

    //获取全部的楼栋信息
         const [build,setBuild]=useState([])
        const getBuild= async ()=>{
          let res =await getAllBuild({})
          console.log("res",res)
          const temarr=res.data.map(item=>({
            label:item.name,
            value:item._id,
            children:item.floorInfo.map(it=>({label:it,value:it}))
          }))
          setBuild(temarr)
        }
    //
  useEffect(()=>{
    getBuild()//获取楼栋
  },[])
  
  //获取全部的房型信息
    const [type,setType]=useState([]);
    const getTypes = async()=>{
      const res=await getAllType({
        limiy:2000 });
        setType(res.data.map(item=>({ label: item.name, value:item._id})))
    }

    useEffect(()=>{
      getTypes()//获取房型
    },[])


  //


  const[showDeleBox,setShowDeleBox]=useState(false)
  const showDel=useCallback(()=>setShowDeleBox(true),[]); 
  
  const handleOk = () => {
    setShowDeleBox(false);
  };
      const [total ,setTotal] = useState(0);
      const [data,setData]=useState([]);
      const [limit,setLimit]=useState(30);
      const [page,setPage]=useState(1);
      
      const[okid,setOkid]=useState(0)
     
      // console.log('data',data)

      const getData=async ()=>{
            const postData = { limit,page };

            // console.log("name",name)
            // console.log('price',price)
            if(name) postData.name = name;
            if(price) postData.price = price;
          
            let res = await getAllRoom(postData)
            const {success,data,count }=res;
            if(success) {
                  setData(data) 
                  setTotal(count)
                }
      }
     

      //条件过滤
      const [name,setName] = useState('');
      const [price,setPrice] =useState('')
      //
       useLayoutEffect(()=>{
           getData();//获取表格
          
       },[limit,page])
    
  
       

    //抽屉 添加房型
     const columns = useMemo(()=>[
        {    
            title: '房間名字',
            dataIndex: 'roomName',
            key: 'roomName',
        },
        {     
            title: '樓層',
            dataIndex: 'floor',
            key: 'floor',
        },
        {
            title:'是否有窗',
            dataIndex:'hasWindow',
            render: (text,record) => {
              return record.hasWindow?<Tag  color="red">有</Tag>:<Tag color="green">无</Tag>
            },
        },
        {
            title:'是否靠近马路',
            dataIndex:'Close2Roaddow',
            render: (text,record) => {
              return record.isClose2Road?<Tag  color="red">有</Tag>:<Tag color="green">无</Tag>
            },
          },
          {
            title:'是否允许吸烟',
            dataIndex:"isSmoke",
            render: (text,record) => {
              return record.isClose2Road?<Tag  color="red">有</Tag>:<Tag color="green">无</Tag>
            },
          },
          {
            title:'是否噪音房',
            dataIndex:"isNoise",
            render: (text,record) => {
              return record.isClose2Road?<Tag  color="red">有</Tag>:<Tag color="green">无</Tag>
            },
          },
          {
            title:'是否是高温房',
            dataIndex:"isHigh",
            render: (text,record) => {
              return record.isClose2Road?<Tag  color="red">有</Tag>:<Tag color="green">无</Tag>
            },
          },
        

        {
          title: '操作',
          valueType: 'option',
          width: 200,
          render: (text,record) => [
            
            <a
                  key="delete"
                  onClick={() => {
                  // handlerDel(record._id)
                    // setOkid(record._id)
                  // console.log(record._id)
                    showConfirm(record._id)
              }}
            >
                   删除
            </a>,
              
            <a
                  key="delete"
                  onClick={() => {
                    openEdit(record)
                    }}
            >
                    修改
            </a>,
        ],
        }
          
         
     

        ])

    const [visible, setVisible] = useState(false);

    const showDrawer = () => {
      setVisible(true);
    };
  
    const onClose = () => {
      setVisible(false);
    };

    const formRef=useRef(null)
   

    //提交房间成功
    const onFinish = async () => {
        const values=  formRef.current.getFieldsValue(true);
        console.log('values',values);    
        
        const{bandf,...postData}=values;
        const [buildId,floor] =bandf;
        console.log('buildId',buildId)
        let res= await addRoom ({...postData,floor,buildId});
          const { success } = res;
        if(!success) notification.open({
          message: '添加失败',
        });
        notification.open({
          message: '添加成功',
        });
        getData();
        setVisible(false);
        formRef.current.resetFields();
      
      
      
  }
    
     //删除房型
       const handlerDel= async(id)=>{    
             console.log('ok11',okid)
             let res =await delRoom({roomid:id})
           
             const { success } = res;
             if(!success) return notification.open({
                message: '删除失败',
             });
             notification.open({
               message: '删除成功',
             });
             getData();
       }

       const { confirm } = Modal;

       const showConfirm = (id) => {
         confirm({
           title: '确认删除?',
           onOk() {          
            handlerDel(id)
           },
           onCancel() {
            handleOk
           },
         });
       };
     

      //修改房型
      const [showEdit,setShowEdit]=useState(false)
      const [curRow,setCurRow] = useState(null)
      const [editRef]=Form.useForm()
      const openEdit=(record)=>{
      setCurRow(record)
           
        setShowEdit(true);
        console.log('record',record)
        editRef.setFieldsValue({
          ...record,
          bandf:[record.buildId,record.floor]
          
        })
     
      }
     

      const handleEdit = async () => {
        
          const values=  editRef.getFieldsValue(true);
          const {bandf,...postData} =values;
          const [buildId,floor]=bandf;
          let res= await editRoom ({
            ...postData,
            roomid:curRow._id,
            buildId,
            floor,
          });
            const { success } = res;
          if(!success) notification.open({
            message: '修改失败',
          });
          notification.open({
            message: '修改成功',
          });
          getData();
          setShowEdit(false);
        
      }
      

      //所在楼栋楼层
      
      const onChange = (value) => {
        console.log(value);
      };

      return (
        <Qfpage title='房间管理'>
          <Row  style={{padding:'8px'}}>
            <Col span={8}>
                <div> 
                    <Button 
                    onClick={showDrawer}
                    >
                        添加新房间
                    </Button>
                </div> 
            </Col>
            <Col span={8}>
            <Input.Group>
                <input 
                  placeholder="请输入你查询的房型"
                  onChange={setName}
                />

                <input 
                  placeholder="请输入你查询的价格"
                  onChange={setPrice}
                />
            </Input.Group>
            </Col>
            <Col span={8}>
            <Button 
            onClick={getData }>立即查询</Button>
            </Col>
          </Row>
            
          
         <Table 
            columns={columns} 
            dataSource={data} 
            pagination={
              {dafaultPageSize:limit,
               total:total,
               onChange({pageSize,current}){
                setPage(current);
                setLimit(pageSize)
          
             }
              }
            }
          />

          {/*抽屉*/}
          <Drawer
            title="添加房间" 
            placement="right" 
            onClose={onClose} 
            visible={visible}
            > 
                <Form
                      ref={formRef}
                      name="basic"
                      labelCol={{
                          span: 8,
                }}
                  wrapperCol={{
                    span: 16,
                  }}
                  initialValues={{
                    remember: true,
                  }}
                      onFinish={onFinish}
                      autoComplete="off"
                      initialValues={{
                        'hasWindow': true,
                        "isClose2Road":false,
                        "isNoise":true,
                        "isHigh":false,  
                        "direction" :"1" ,      
                }}
              >
                <Form.Item
                   label="房间名称"
                   name='roomName'
                   rules={[
                    {
                      required: true,
                      message: '填写房间名称',
                    }]}
                >
                  <Input placeholder=''></Input>
                </Form.Item>
                <Form.Item
                label="所在楼栋楼层"
                name="bandf"
                rules={[
                  {
                    required: true,
                    message: '填写所在楼栋楼层',
                  }]}
                >
                <Cascader 
                    options={build} 
                    onChange={onChange} 
                    placeholder="Please select" 
                />
               </Form.Item>

               <Form.Item
                label="选择房型"
                name="type"
                rules={[
                  {
                    required: true,
                    message: '选择所在楼栋楼层',
                  }]}
                >
              <Select options={type}></Select>
               </Form.Item>
                <Form.Item
                   label="内线电话"
                   name='phone4in'
                   rules={[
                    {
                      required: true,
                      message: '填写内线电话',
                    }]}
                >
                  <Input placeholder=''></Input>
                </Form.Item>
                <Form.Item 
                label="方向朝向" 
                name="direction"             
                >
                       <Radio.Group defaultValue="1">
                                <Radio.Button value="1">东</Radio.Button>
                                <Radio.Button value="2">西</Radio.Button>
                                <Radio.Button value="3">南</Radio.Button>
                                <Radio.Button value="4">北</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    
                    <Form.Item label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group> 
                    </Form.Item>      

                <Button 
                    type="primary" 
                    htmlType="submit"
                >
                   提交
                  </Button>
              </Form>

      </Drawer>
     
     
      {/*修改房型*/}
      <Drawer
            title="立即修改" 
            placement="right" 
            onClose={()=> setShowEdit(false) }
            visible={showEdit}
            forceRender
            
            > 
            <Form
                      form={editRef}
                      name="basic"
                      labelCol={{
                          span: 8,
                }}
                  wrapperCol={{
                    span: 16,
                  }}
                  initialValues={{
                    remember: true,
                  }}
                      onFinish={handleEdit}
                      autoComplete="off"
                      initialValues={{
                        'hasWindow': true,
                        "isClose2Road":false,
                        "isNoise":true,
                        "isHigh":false,  
                        "direction" :"1" ,      
                }}
              >
                <Form.Item
                   label="房间名称"
                   name='roomName'
                   rules={[
                    {
                      required: true,
                      message: '填写房间名称',
                    }]}
                >
                  <Input placeholder=''></Input>
                </Form.Item>
                <Form.Item
                label="所在楼栋楼层"
                name="bandf"
                rules={[
                  {
                    required: true,
                    message: '填写所在楼栋楼层',
                  }]}
                >
                <Cascader 
                    options={build} 
                    onChange={onChange} 
                    placeholder="Please select" 
                />
               </Form.Item>

               <Form.Item
                label="选择房型"
                name="type"
                rules={[
                  {
                    required: true,
                    message: '选择所在楼栋楼层',
                  }]}
                >
              <Select options={type}></Select>
               </Form.Item>
                <Form.Item
                   label="内线电话"
                   name='phone4in'
                   rules={[
                    {
                      required: true,
                      message: '填写内线电话',
                    }]}
                >
                  <Input placeholder=''></Input>
                </Form.Item>
                <Form.Item 
                label="方向朝向" 
                name="direction"             
                >
                       <Radio.Group defaultValue="1">
                                <Radio.Button value="1">东</Radio.Button>
                                <Radio.Button value="2">西</Radio.Button>
                                <Radio.Button value="3">南</Radio.Button>
                                <Radio.Button value="4">北</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否有窗户" name="hasWindow">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否靠近马路" name="isClose2Road">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否允许吸烟" name="isSmoke">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    <Form.Item label="是否是噪音房" name="isNoise">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group>       
                    </Form.Item>
                    
                    <Form.Item label="是否是高温房" name="isHigh">
                        <Radio.Group defaultValue={false}>
                                <Radio.Button value={true}>是</Radio.Button>
                                <Radio.Button value={false}>否</Radio.Button>
                        </Radio.Group> 
                    </Form.Item>      

                <Button 
                    type="primary" 
                    htmlType="submit"
                >
                   提交
                  </Button>
              </Form>
      </Drawer>
       
      
        </Qfpage>
    )
}
export default RoomList;    